package com.rexolar.openapi.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rexolar.openapi.enums.ErrorCodeEnum;
import com.rexolar.openapi.exception.TokenException;
import com.rexolar.openapi.service.AuthCheckService;
import com.rexolar.openapi.utlis.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;

/**
 * @Description 用户认证拦截器
 * @Author  zhusiyu
 * @Date 2024/09/18
 * @Version 1.0
 */
@Component
@Slf4j
public class AuthInterceptor extends BaseOpenApiInterceptor {
    @Resource
    AuthCheckService authCheckService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws IOException {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            log.debug("OPTIONS请求");

            return true; // 不拦截 OPTIONS 请求
        }
        if (skipCheckUri(request.getRequestURI())) {return true;}
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        log.debug("requestURI=" + requestURI);
        if(StringUtils.isBlank(token)){
            log.error("AuthInterceptor token is null");
            throw new TokenException(ErrorCodeEnum.USER_LOGIN_NO_TOKEN);
        }
        boolean verifyToken = authCheckService.checkToken(token);
        if (!verifyToken){
            throw new TokenException(ErrorCodeEnum.USER_LOGIN_TOKEN_EXPIRE);
        }

        return true;
    }
    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }
    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
    }

    public static void main(String[] args) {
        String tokenStr = "dXl0MjlNeE44Y21BMFBtd2lpcHBWMEx6TGJoTk9WR0JHc1RFdGZQTXFyRkVkbEVqZnNONlIxNjNZTFlTYWJOOA==";
        String base64String = Base64.getEncoder().encodeToString(tokenStr.getBytes());
        System.out.println(base64String);
    }


}
